Inheritance
Tags: #◇Computer Science #◇CCPROG3 #◇Inheritance #◇Code Snippets #◇M5
◇Key Definitions
Inheritance is an OOP principle where a new class (subclass) acquires the properties and behaviors (fields and methods) of an existing class (superclass).
◇Theoretical Framework
Inherited members can be used as-is, overridden, or hidden. Java supports single inheritance of state (a class can only extend one superclass) but multiple inheritance of type (a class can implement multiple interfaces). Enhances code reusability and establishes an "is-a" relationship.
◇Code Implementation
// Superclass
class Vehicle {
protected String brand = "Ford";
public void honk() {
System.out.println("Tuut, tuut!");
}
}
// Subclass extending Vehicle
class Car extends Vehicle {
private String modelName = "Mustang";
public void printDetails() {
System.out.println(brand + " " + modelName);
}
// Overriding the superclass method
@Override
public void honk() {
System.out.println("Beep, beep!");
}
}
◇Syntax Breakdown
extends: Keyword used to inherit from a class. super: Keyword used to refer to the immediate parent class object. @Override: Annotation to indicate that the child class method is over-writing its base class method. protected: Access modifier allowing subclasses to access the member.
◇Complexity Analysis
Inheritance structures create a virtual method table (vtable) for dynamic method dispatch. Calling overridden methods has a negligible O(1) overhead. Deep inheritance trees can make code difficult to maintain and trace (the "yo-yo problem").
◇References & Navigation
- Previous Topic: ◇Collections
- Next Topic: ◇Graphical User Interfaces and Event Handling
- Related Notes: ◇Overview of Programming Languages
ACTIVE RECALL VERIFICATION
Select an answer to verify conceptual comprehension and reveal the technical rationale.
What is Inheritance in the context of Object-Oriented Programming?
Which keyword is used in Java to indicate that a child class method is over-writing its base class method?
In Java, what is meant by the rule that a class supports "single inheritance of state"?
What is the purpose of the super keyword in a subclass?
What potential maintainability issue arises from deep inheritance trees?